import type { ComponentStyleIdType } from '../../../types/interfaces'
import { BaseModule } from '../../../lib/abstract'
import { PageManager } from '../../../lib/abstract/page_manager'
import { ComponentStyleId, logger } from '../../../types/constants'
import { ThemeType } from '../../../types/interfaces'
import { StyleOperateType } from '../../../user_center/tab/personalization/page_theme/types'
import { ConfigManager } from '../../config_manager'

interface Config {
  enabled?: boolean
}

export class ThemeInherit extends BaseModule {
  readonly id: string = 'theme_inherit'
  readonly styleId: string = ComponentStyleId[this.name]
  isInitialized: boolean = false
  readonly supportedPlatforms: string[] = ConfigManager.getInstance().moduleSupportedPlatforms(this.name)
  private static instance: ThemeInherit
  private pageManager: PageManager = PageManager.getInstance()

  config: Config = {
    enabled: true,
  }

  get name(): ComponentStyleIdType {
    return 'ThemeInherit'
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ThemeInherit {
    if (!ThemeInherit.instance) {
      ThemeInherit.instance = new ThemeInherit()
    }
    return ThemeInherit.instance
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.initTheme()
  }

  onToggleCallback(_id: string, checked: boolean): void {
    super.onToggleCallback(_id, checked)
  }

  /**
   * 初始化主题
   */
  initTheme(): void {
    const platformTheme = this.pageManager.hasUniformThemes()
    const pageTheme = this.pageManager.getCurrentPageTheme()

    let theme: ThemeType
    let styleOperateType: StyleOperateType = StyleOperateType.Keep

    if (pageTheme) {
      theme = pageTheme as ThemeType
    }
    else if (!pageTheme && platformTheme) {
      theme = platformTheme as ThemeType
      styleOperateType = StyleOperateType.Update
    }
    else {
      theme = ThemeType.DARK
      styleOperateType = StyleOperateType.Update
    }

    this.pageManager.recordLatestThemeMeta(theme, styleOperateType)
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)

    this.initTheme()

    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }

  getStyles(): string {
    return `
`
  }
}
